/** @odoo-module **/
import init_grid_options from '../ag_grid/gridOptions.js'


const {
    markup,
    Component,
    onWillStart,
    useEnv,
    useSubEnv,
    useChildSubEnv,
    useRef,
    useState,
    mount,
    xml,
    whenReady,
    onMounted,
    onError,
    loadFile,
    onWillUpdateProps,
    useEffect,
    useComponent
} = owl;

class DishListModal extends Component {
    static template = xml`
        <!--菜品列表 -->
        <div class="modal fade " id="dishListModal">
          <div class="modal-dialog  modal-xl modal-dialog-centered">
            <div class="modal-content">
              <div class="modal-header">
                <h1 class="modal-title fs-5"><t t-esc="state.headTitle"/></h1>
                  <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
              </div>
                <div class="modal-body">
                  <div class="row g-3 mb-3">
                      <div class="col-auto" t-if="props.is_open">
                        <select class="form-select form-select-sm" t-model="state.form.plan_top_category_id" t-on-change="search" t-att-disabled="props.limitCategory">
                              <option value="" name="plan_top_category_id">请选择食材</option>
                            <t t-foreach="state.plan_top_category" t-as="v" t-key="v_index">
                                    <option t-att-value="v.id" name="plan_top_category_id"> <t t-esc="v.name"/></option>
                                </t>
                        </select>
                      </div>
                      <div class="col-auto">
                            <input type="text" class="form-control form-control-sm" placeholder="请输入菜品名称"
                                   t-model="state.form.name" t-on-keyup="search"/>
                      </div>
                      <div class="col-auto">
                           <label class="col-form-label col-form-label-sm">辣度</label>
                      </div>
                      <div class="col-auto"  t-if="props.is_open">
                          <select class="form-select form-select-sm" t-model="state.form.spicy" t-on-change="search">
                                      <option value="" name="spicy">请选择</option>
                              <option value="spicy1" name="spicy">不辣</option>
                              <option value="spicy2" name="spicy">微辣</option>
                              <option value="spicy3" name="spicy">中辣</option>
                              <option value="spicy4" name="spicy">特辣</option>
                                </select>
                      </div>
                      <div class="col-auto">
                           <label class="col-form-label col-form-label-sm">颜色</label>
                      </div>
                      <div class="col-auto"  t-if="props.is_open">
                        <select class="form-select form-select-sm" t-model="state.form.color_id" t-on-change="search">
                                      <option value="" name="color_id">请选择</option>
                            <t t-foreach="props.dish_material_color_category" t-as="v" t-key="v_index">
                                            <option t-att-value="v.id" name="color_id"><t t-esc="v.name_cn || v.name"/></option>
                                        </t>
                        </select>
                      </div>
                      <div class="col-auto">
                           <label class="col-form-label col-form-label-sm">成本</label>
                      </div>
                      <div class="col-auto"  t-if="props.is_open">
                        <select class="form-select form-select-sm" t-model="state.form.dish_cost" t-on-change="search">
                             <option value="" name="dish_cost">请选择</option>
                            <t t-foreach="state.costOptions" t-as="v" t-key="v_index">
                                <option t-att-value="v.id" name="dish_cost"><t t-esc="v.name"/></option>
                             </t>
                        </select>
                      </div>

                      <div class="col-auto"  t-if="props.is_open">
                        <select class="form-select form-select-sm" t-model="state.form.dish_sub_category_id" t-on-change="search">
                                      <option value="" name="dish_sub_category_id">请选择</option>
                            <t t-foreach="dish_sub_category" t-as="v" t-key="v_index">
                                            <option t-att-value="v.id" name="dish_sub_category_id"><t t-esc="v.name"/></option>
                                        </t>
                        </select>
                      </div>


                      <!--<div class="col-auto">-->
                      <!--<button type="button" class="btn btn-primary btn-sm" t-on-click.stop="search">搜索</button>-->
                      <!--</div>-->
                    </div>
                    <div t-ref="dishGrid" style="width: 100%;height:400px" class="ag-theme-balham myGrid"/>

              </div>
                <div class="modal-footer">
                  <div class="text-danger" style="flex:1">
                      <t t-esc="state.msg"/>
                  </div>
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" t-on-click.stop="handleSubmitModel">确定</button>
              </div>
            </div>
          </div>
        </div>
`;
    static props = {
        dish_key: {type: Array,optional:true},
        is_open: {type: Boolean,optional:true},
        data: {type: Object,optional:true},
        dish_material_color_category: {type: Array,optional:true},
        plan_top_category:{type: Array,optional:true},
        limitCategory: {type: Boolean,optional:true},
        dish_sub_category: {type: Array,optional:true}
    };

    setup() {
        this.state = useState({
            headTitle: '菜品列表',
            form: {},
            msg: '',
            costOptions: [
                {name: '0~0.5', id: '0,0.5'},
                {name: '0.5~1', id: '0.5,1'},
                {name: '1~1.5', id: '1,1.5'},
                {name: '1.5~2', id: '1.5,2'},
                {name: '2+', id: '2'},
            ],
            plan_top_category:[]
        })

        this.dishGrid_ref = useRef('dishGrid');
        this.filterModel = {};

        onMounted(() => {
            let _this = this;
            this.dishListModal = new bootstrap.Modal('#dishListModal', {});

            document.getElementById('dishListModal').addEventListener('hidden.bs.modal', event => {
                _this.state.form = {};
                _this.env.closeDishListModal();
            })

            this.dishGridOptions = Object.assign({}, init_grid_options(), {
                rowData: this.props.dish_key,
                defaultColDef: {
                    filter: true,  //开启刷选
                },
                suppressRowClickSelection: false,
                columnDefs: [
                    {
                        headerName: '菜品名称',
                        field: 'name',
                        menuTabs: [],
                        width: 160,
                        editable: false,
                        checkboxSelection: true, //设置为true显示为复选框
                        filter: 'agTextColumnFilter'
                        // headerCheckboxSelection: true, //表头是否也显示复选框，全选反选用
                    },
                    {
                        headerName: '次级类别',
                        field: 'dish_sub_category_id',
                        menuTabs: [],
                        flex: 1,
                        editable: false,
                        filter: 'agNumberColumnFilter',
                        hide: true
                    },
                    {
                        headerName: '类别',
                        field: 'dish_top_category_id',
                        menuTabs: [],
                        flex: 1,
                        editable: false,
                        filter: 'agNumberColumnFilter',
                        hide: true
                    },
                    {
                        headerName: '食材',
                        field: 'plan_top_category_id',
                        menuTabs: [],
                        flex: 1,
                        editable: false,
                        filter: 'agNumberColumnFilter',
                        hide: true
                    },
                    {
                        headerName: '颜色',
                        field: 'color_id',
                        editable: false,
                        filter: 'agTextColumnFilter',
                        hide: true
                    },
                    {
                        headerName: '价格',
                        field: 'dish_cost',
                        menuTabs: [],
                        editable: false,
                        sortable: true,
                        filter: 'agNumberColumnFilter',
                        width: 100
                    },
                    {
                        headerName: '辣度',
                        field: 'spicy',
                        menuTabs: [],
                        editable: false,
                        filter: 'agTextColumnFilter',
                        cellRenderer: (params) => {
                            if (params.value == "" || params.value == undefined) return "";
                            let el = document.createElement('div');
                            let _html = '';
                            _html += _this.env.spicyHtml(params.value);
                            el.innerHTML = _html;
                            return el;
                        },
                        width: 100
                    },
                    {
                        headerName: '食材配比',
                        field: 'dish_bom_str',
                        flex: 1,
                        editable: false,
                        menuTabs: [],
                        cellRenderer: (params) => {
                            if (params.value == "" || params.value == undefined) return "";
                            return params.value.split('/').join('，');

                        }
                    },
                ],
                context: {
                    owl_widget: _this
                },
                onSelectionChanged: () => {
                    const selRows = _this.dishGridOptions.api.getSelectedRows();
                    if (selRows.length == 0) {
                        _this.state.msg = '请勾选菜品';
                    } else {
                        _this.state.msg = '';
                    }
                }
            });

            this.dishGrid = new agGrid.Grid(this.dishGrid_ref.el, this.dishGridOptions);
        })

        onWillUpdateProps(nextProps => {
            // console.log(nextProps);
            if (nextProps.is_open) {
                return this.openModel(nextProps.data);
            }
        });

        this.handleSubmitModel = _.debounce(this.submitModel,300);
    }

    get dish_sub_category(){
        let dish_sub_category = this.props.dish_sub_category.filter(v=>v.dish_top_category_id == this.props.data.filterModel.dish_top_category_id);
        return dish_sub_category || [];
    }

    openModel(data) {
        this.dishGridOptions.api.setRowData(this.props.dish_key);

        let filterModel = data.filterModel || false;
        let headTitle = '菜品列表';
        if (filterModel) {
            let _model = {};
            _model.dish_top_category_id = {
                type: 'equals', filter: filterModel.dish_top_category_id
            }
            this.filterModel = _model;
            this.state.form.plan_top_category_id = filterModel.plan_top_category_id;
            this.search();
            headTitle = headTitle + '-' + filterModel.dish_top_category_name_cn;
        }
        this.state.headTitle = headTitle;
        this.state.plan_top_category = this.env.planTopCategoryArr(filterModel.dish_top_category_id);
        this.dishListModal.show();
    }

    search() {
        for (let key in this.state.form) {
            let v = this.state.form[key];
            if (key == 'dish_cost' && v != '') {
                let _costModel = {};
                // let costFilterComponent = this.dishGridOptions.api.getFilterInstance('dish_cost');
                let min = Number(v.split(',')[0]);
                let max = Number(v.split(',')[1] || '0');
                if (min === 0) {
                    _costModel = {
                        type: 'lessThan',
                        filter: max,
                        filterTo: null,
                    };
                    // costFilterComponent.setModel(_costModel);
                } else if (max === 0) {
                    _costModel = {
                        type: 'greaterThan',
                        filter: min,
                        filterTo: null,
                    };
                } else {
                    _costModel = {
                        type: 'inRange',
                        filter: min,
                        filterTo: max,
                    };
                }
                this.filterModel[key] = _costModel;
            } else {
                this.filterModel[key] = {
                    filterType: 'text',
                    type: 'contains',
                    filter: v
                }
            }
        }
        // console.log(this.filterModel);
        this.dishGridOptions.api.setFilterModel(this.filterModel);
        this.dishGridOptions.api.onFilterChanged();
    }

    // 提交
    submitModel() {
        const selRows = this.dishGridOptions.api.getSelectedRows();
        if (selRows.length == 0) {
            this.state.msg = '请勾选菜品';
            return;
        }
        this.env.selectDish(selRows[0]);
        this.dishListModal.hide();
    }
}
DishListModal.defaultProps = {
    limitCategory: false,
    plan_top_category:[]
}

export {
    DishListModal
}
